<script lang="ts" setup>
import {computed, nextTick, onBeforeMount, onMounted, reactive, ref, watch} from 'vue';
import util from "@/utils/util";
import { useRoute} from "vue-router";

let softListBoxRef = ref();
let scollHeight = ref(500);

//分类处理
let cateArr = reactive<Soft.Cate[]>([])
async function getCate() {
  let res = await util.remote<Config.All>('config')
  return res.cate;
}

async function initCate() {
  let cate = await getCate()
  cateArr.push({code:'all',title:'所有'})
  for (const cateKey in cate) {
    cateArr.push({code:cateKey,title:cate[cateKey]})
  }
  cateArr.push({code:'installed',title:'已安装'})
}
initCate();

let softList = ref<Soft.Item[]>([])
async function getSoftList() {
  let tempSoft = await util.remote<Soft.Item[]>('soft')
  softList.value = tempSoft
  // softList.value = tempSoft.map(i=>{
  //   i.key = i.type+'-'+i.name + '-'+i.ver;
  //   return i
  // })
  getHeight();
}
getSoftList()


const currTab = ref<string>('all');

//let expandedRowKeys = ref<string[]>([]);

let ingSoftList = reactive<{[key:string]:any}>({});
let expandedRowKeys = computed<string[]>(() => Object.keys(ingSoftList))


const columns = [
  {
    title: '软件名称',
    dataIndex: 'name',
    key: 'name',
    width:200
  },
  {
    title: '说明',
    dataIndex: 'desc',
    key: 'desc',
    ellipsis: true,
  },
  {
    title: '操作',
    key: 'action',
    width: 120
  },
];

const route = useRoute()
watch(route,(o,n)=>{
    if(route.path == '/soft'){
      nextTick(()=>{
        scollHeight.value = softListBoxRef.value?.offsetHeight
      })
    }
})

function getHeight(){
    if (softListBoxRef.value) {
      if(route.path == '/soft'){
        scollHeight.value = softListBoxRef.value?.offsetHeight
      }
    }
}
onMounted(()=>{
  getHeight()
  window.addEventListener("resize", getHeight);
})

onBeforeMount(()=>{
  window.removeEventListener("resize", getHeight);
})

let currSoftList = computed(()=>{
  let ct = currTab.value;
  if(currTab.value === 'all' ){
    return softList.value
  }
  if(currTab.value === 'installed'){
     return softList.value.filter(i=>{
       return i.install !== '0' && i.install !== '1'
     })
  }
  return softList.value.filter(i=>{ return i.type === ct})
})

function doInstall(soft:Soft.Item){
  ingSoftList[soft.key!] = {
    "total":0,
    "downed":0,
    "percent":0,
    "status":"active",
    "text":"准备中"
  } as Soft.Percent;
  soft.install = '1';
  aardio.down(JSON.stringify(soft))
}

function percentNum(d:number,t:number){
  if(t==0 || d==0){return 0}
  return  parseInt((d / t * 100) +'');
}

window.upInstallPercent = (key:string,percent:Partial<Soft.Percent>,install?:string) =>{
  console.log('percent',percent,install)
  ingSoftList[key] = Object.assign({},ingSoftList[key],percent);
  //返回下载成功
  if(percent.status == 'success'){
    ingSoftList[key].downed = ingSoftList[key].total = 1000;
  }
  install = install || '1';
  let softArr = softList.value.filter(i=>i.key == key);
  if(softArr.length){
    softArr[0].install = install+'';
  }
  console.log(ingSoftList)
  //返回安装路径（安装成功）
  if(install !=='1'){
    setTimeout(()=>{
      delete ingSoftList[key];
    },1500)
  }

}

</script>

<template>
  <div style="padding: 15px;">
      <div>
        <div style="text-align: center;">
          <a-radio-group v-model:value="currTab" button-style="solid" >
            <a-radio-button v-for="cate in cateArr" :key="cate.code" :value="cate.code">{{ cate.title }}</a-radio-button>
          </a-radio-group>
        </div>

        <div ref="softListBoxRef">



        <a-card  :body-style="{padding:'0px'}" style="margin-top: 16px;height: calc(100vh - 120px); overflow: hidden;" >
          <a-table sticky :scroll=" { y: scollHeight - 40 }" :dataSource="currSoftList" :columns="columns" size="small" :pagination="false" :showExpandColumn="false" row-key="key" :expandedRowKeys="expandedRowKeys">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <a-button v-if="record.install == '0' || record.install == '1' " :loading="record.install == '1'" type="primary" size="small" @click="doInstall(record)">安装</a-button>
                <a-button size="small"  v-else>目录</a-button>
              </template>
              <template v-if="column.key === 'name'">
                {{record.name}}{{record.ver ? '-'+record.ver : '' }}
              </template>
            </template>
            <template #expandedRowRender="{ record }">
              <div style="width: 98%" v-if="ingSoftList[record.key]">
              <a-progress
                  size="small"
                  :stroke-color="{
                    '0%': '#108ee9',
                    '100%': '#87d068',
                  }"
                  :percent="percentNum(ingSoftList[record.key].downed,ingSoftList[record.key].total)"
                  :status="ingSoftList[record.key].status"
              >
                <template #format="percent">
                  <span style="color: red">{{ ingSoftList[record.key].text }}</span>
                </template>
              </a-progress>
              </div>
            </template>
          </a-table>
        </a-card>
        </div>
      </div>
  </div>
</template>
<style scoped lang="less">
::v-deep(.ant-table-expanded-row){
  .ant-table-cell{
    padding: 0 10px !important;
  }
  .ant-progress{
    margin-bottom: 5px;
  }
}
</style>